// 全局定位工具：只在需要时请求一次定位，并在内存与本地缓存中复用

let cachedLocation = null;

function getUserLocation(forceRefresh = false) {
  return new Promise((resolve, reject) => {
    if (!forceRefresh && cachedLocation) {
      return resolve(cachedLocation);
    }

    // 尝试先用本地缓存兜底（避免每次冷启动都立刻失败）
    if (!forceRefresh && !cachedLocation) {
      const last = wx.getStorageSync('lastLocation');
      if (last && last.latitude && last.longitude) {
        cachedLocation = last;
        return resolve(last);
      }
    }

    wx.getLocation({
      type: 'gcj02',
      success(res) {
        cachedLocation = {
          latitude: res.latitude,
          longitude: res.longitude
        };
        wx.setStorageSync('lastLocation', cachedLocation);
        resolve(cachedLocation);
      },
      fail(err) {
        const last = wx.getStorageSync('lastLocation');
        if (last && last.latitude && last.longitude) {
          cachedLocation = last;
          resolve(last);
        } else {
          reject(err);
        }
      }
    });
  });
}

module.exports = {
  getUserLocation
};
